package vip.fuxk.neav.config;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.exception.StatusException;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.core.route.PathRule;
import org.noear.solon.core.util.KeyValues;
import org.noear.solon.core.util.MultiMap;
import vip.fuxk.neav.service.SubAppService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
//@Component(index = 0)
public class SubAppFilter  implements Filter {

    @Inject
    SubAppService subAppService;

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        boolean notHandler = false;
        try {
            // 优先执行主应用请求
            chain.doFilter(ctx);
            notHandler = !ctx.getHandled();
        } catch (StatusException e) {
            if(e.getCode() == 404){
                notHandler = true;
            }
        }
        // 主应用未处理，则分发到子应用
        if(notHandler){
            Map.Entry<String, PathRule> entry = subAppService.tryMatchSub(ctx.pathNew());
           if(entry!=null){
               String server = subAppService.getServerByGroup(entry.getKey());
               log.debug("sub app match ... ");
               MultiMap<String> keyValues = ctx.paramMap();
               Map<String, Object> map = new HashMap<>();
               for (KeyValues<String> keyValue : keyValues) {
                   List<String> values = keyValue.getValues();
                   if(values == null || values.isEmpty()){
                       continue;
                   }
                   if( values.size() == 1){
                       map.put(keyValue.getKey(),keyValue.getFirstValue());
                   }else{
                       map.put(keyValue.getKey(),keyValue.getValues());
                   }

               }

               HttpResponse response = HttpRequest.of(server)
                       .method(Method.valueOf(ctx.method().toUpperCase()))
                       .form(map)
                       .timeout(3000).execute();

               Map<String, List<String>> headers = response.headers();

               System.out.println("body");

           }
        }
    }
}
